import * as mqtt from "mqtt";
import { MQ_SERVICE,MQ_OPTIONS } from '@/config/linkparam'
const mqForMqtt = {
    /**
     * 
     * @param {*} responseMsgCallback  订阅消息回调
     * @returns 
     */
    connect(responseMsgCallback,closeCallBack) {
        return new Promise((resolve, reject) => {
            const client = mqtt.connect(MQ_SERVICE,MQ_OPTIONS);
            client.on("message", responseMsgCallback);
            //重连
            client.on('reconnect', () => {
                console.log('正在重连 :>> ');
            });
            //服务器断开
            client.on('disconnect', (packet) => {
                console.log('服务器断开 :>> ',packet);
            });
            //连接关闭
            client.on('close', closeCallBack);

            //连接失败
            client.on('error', (error) => {
                console.log("连接失败", error)
                client.end();
                reject();
            })
            client.on('offline',()=>{
                console.log("客户端离线");
            });
            //建立连接返回client 成功
             client.on('connect', () => {
                console.log('连接成功 :>> ',new Date().toLocaleString());
                resolve(client);   
            });
            
        })

    },
    /**
     * 订阅
     * @param {*} client 
     * @param {*} topic 
     * @param {*} options 
     */
    subscribe(client, topic, options = { qos: 2 }) {
        client.subscribe(topic, options, (error, res) => {
            if (!error) {
                console.log('订阅成功', res)
            } else {
                console.log('订阅失败', error)
            }
        });
    },
    /**
     * 取消订阅
     * @param {*} client 
     * @param {*} topic 
     */
    unsubscribe(client, topic) {
        client.unsubscribe(topic, (error) => {
            if (!error) {
                console.log('取消订阅成功',)
            } else {
                console.log('取消订阅失败', error)
            }
        });
    },
    /**
     * 发布
     * @param {*} client 客户端
     * @param {*} topic 主题
     * @param {*} message 消息
     * @param {*} options 配置  
     * https://github.com/mqttjs/MQTT.js#publish
     */
    publish(client, topic, message, options = { qos: 2 }) {
        client.publish(topic, message, options, (error) => {
            if (!error) {
                console.log('发布成功',)
            } else {
                console.log('发布失败', error)
            }
        });
    },
    /**
     * 关闭连接
     * @param {*} client 
     */
    disconnect(client) {
        client.end();
    },
    /**
     * 对消息进行解码操作
     * @param {*} charset 
     * @returns 
     */
    unit8ArrayDecode(message, charset = 'UTF-8') {
        return new TextDecoder(charset).decode(message);
    }
}
export default mqForMqtt